import api, { messageApi as messageApiInstance } from './api'
import { KafkaMessage, TopicInfo } from '@/stores/kafkaStore'

export interface KafkaConnectionTest {
  success: boolean
  message: string
  brokers: number
}

export interface CreateTopicRequest {
  name: string
  num_partitions: number
  replication_factor: number
}

export interface SendMessageRequest {
  topic: string
  value: any
  key?: string
  partition?: number
  message_format?: string
  headers?: Record<string, string>
}

export interface KafkaConfig {
  bootstrap_servers: string
  security_protocol: string
  sasl_mechanism: string
  sasl_username?: string
  sasl_password?: string
  api_version?: string
}

// Kafka连接相关
export const kafkaApi = {
  // 测试连接
  testConnection: (): Promise<KafkaConnectionTest> =>
    api.get('/kafka/connection/test'),
  
  // 获取Topic列表
  getTopics: (): Promise<string[]> =>
    api.get('/kafka/topics'),
  
  // 获取Topic信息
  getTopicInfo: (topicName: string): Promise<TopicInfo> =>
    api.get(`/kafka/topics/${topicName}`),
  
  // 获取集群信息
  getClusterInfo: () =>
    api.get('/kafka/cluster/info'),
}

// Topic管理相关
export const topicApi = {
  // 创建Topic
  createTopic: (data: CreateTopicRequest) =>
    api.post('/topics/create', data),
  
  // 删除Topic
  deleteTopic: (topicName: string) =>
    api.delete(`/topics/${topicName}`),
}

// 消息加载模式
export type MessageLoadMode = 'all' | 'earliest'

// 消息加载选项
export interface MessageLoadOptions {
  maxMessages?: number
  loadMode?: MessageLoadMode
  fromBeginning?: boolean
  partition?: number  // 添加分区筛选
}

// 消息相关
export const messageApi = {
  // 获取消息（增强版）
  getMessages: (
    topicName: string,
    options: MessageLoadOptions = {}
  ): Promise<KafkaMessage[]> => {
    const {
      maxMessages = 100,
      loadMode = 'earliest',
      fromBeginning = false,
      partition
    } = options

    const params = new URLSearchParams({
      load_mode: loadMode,
      from_beginning: fromBeginning.toString()
    })

    // 只有在非全量模式时才传递max_messages参数
    if (loadMode !== 'all') {
      params.append('max_messages', maxMessages.toString())
    }

    // 添加分区参数
    if (partition !== undefined) {
      params.append('partition', partition.toString())
    }

    return messageApiInstance.get(`/messages/${topicName}?${params}`)
  },

  // 发送消息
  sendMessage: (data: SendMessageRequest) =>
    api.post('/messages/send', data),
}

// 设置相关
export const settingsApi = {
  // 保存Kafka配置
  saveKafkaConfig: (config: KafkaConfig) =>
    api.post('/settings/kafka', config),

  // 获取Kafka配置
  getKafkaConfig: (): Promise<KafkaConfig> =>
    api.get('/settings/kafka'),

  // 测试Kafka配置
  testKafkaConfig: (config: KafkaConfig): Promise<KafkaConnectionTest> =>
    api.post('/settings/kafka/test', config),

  // 删除Kafka配置
  deleteKafkaConfig: () =>
    api.delete('/settings/kafka'),
}
